<template>
	<view class="painting-index" ref="uv-back-top">
		<headers :state="state" @custom-event="e=>state = e"></headers>
		<el-container
			:style="$uv.os() == 'windows'?'height: calc(100vh - 50px);':'height: calc(100vh - 115px);overflow: auto;'">
			<asided :aicurrent="aicurrent" :asideW="state?70:0" @custom-type="e=>aiType = e" @custom-list="e=>lists = e"
				@custom-event="customI">
			</asided>
			<view dfes="retre"
				:style="$uv.os() == 'windows'?'width: 100%;display: flex;justify-content: center;flex-wrap: nowrap;':'width: 100%;margin-right:10px;display: flex;justify-content: center;flex-wrap: wrap;'">
				<view
					style="background-color: #eeeeee;max-width: 450px;margin:10px;padding: 10px;borber:1px solid #f2f2f2;border-radius: 10px;">
					<flux v-if="aiType=='flux'" :fluxInfo="taskInfo" :type="aiType" @flux="flux"
						@focus="$uv.os() != 'windows'?state = false:''">
					</flux>
					<dalle v-if="aiType=='dalle'" :dalleInfo="taskInfo" :type="aiType"
						@focus="$uv.os() != 'windows'?state = false:''" @dalle="dalle">
					</dalle>
					<mjy v-if="aiType=='mjy'" :mjyInfo="taskInfo" :type="aiType" @custom-event="e =>strType = e"
						@focus="$uv.os() != 'windows'?state = false:''" :assembly="true" @mjy="flux">
					</mjy>
					<gpt v-if="aiType=='gpt'" :gptInfo="taskInfo" :type="aiType"
						@focus="$uv.os() != 'windows'?state = false:''" @gpt="gpt">
					</gpt>
					<!-- <kling v-if="aiType=='kling'" :lists="lists[aicurrent]" :taskInfo="taskInfo" :type="aiType"
						@custom-event="e =>strType = e" @focus="$uv.os() != 'windows'?state = false:''"
						:aicurrent="aicurrent" :assembly="true" @kling="kling">
					</kling> -->
				</view>
				<el-container>
					<el-main style="margin-top:0px;padding:0px 15px;">
						<view class="middle">
							<view v-for="(item,index) in list" :key="index">
								<uv-text v-if="cTime(item.createdAt,list,index)"
									:customStyle="'margin-bottom: 10px;border-radius:5px;padding:2px 5px;background-color:'+dialogueColor"
									:text="times(item.createdAt)" align="center"></uv-text>
								<view :class="item.role=='user'?'middle_item user':'middle_item'">
									<view v-if="isPc" class="fill">
										<el-image fit="fill"
											:src="item.role=='user'?vuex_user.portrait:'/static/ai.svg'"></el-image>
									</view>
									<view :class="isPc?'middle_pc':'middle_os'"
										:style="'background-color:'+dialogueColor+';'">
										<view
											v-if="(item.data && item.data[0].revised_prompt) ||item.revised_prompt||item.content||item.prompt">
											<contents :style="'background-color:'+dialogueColor" :type="tabbarsValue"
												:aiType="aiType" :shows="show" :taskid="taskid" :item="item"
												:index="index">
											</contents>
										</view>
										<view v-else :str="show = 0" 重置分享>
											<uv-loading-icon color="red"></uv-loading-icon>
										</view>
									</view>
									<view v-if="$uv.os() == 'windows'" style="opacity: 0;width: 40px;">00000</view>
								</view>
							</view>
						</view>
					</el-main>
				</el-container>
			</view>
			<view v-if="$uv.os() == 'windows'">
				<view class="p_content" :style="footers?'width:'+historyW*4+'px':'width:'+historyW+'px'">
					<view style="position: fixed;margin-left: 0px;margin-top: 45vh;z-index:1;">
						<view class="cursor-pointer" style="margin-left: -35px;background-color: #f2f2f2;padding: 10px;"
							@click="footers = !footers"
							:style="'width:200px;display: flex;justify-content: center;align-items: center;border-radius: 50%;width:20px ; height: 20px;'">
							<i v-if="footers" class="el-icon-arrow-right" style="font-size: 25px;"></i>
							<i v-else class="el-icon-arrow-left" style="font-size: 25px;"></i>
						</view>
					</view>
					<view class=""
						style="display: flex;justify-content: flex-start;align-items: center;height: calc(100vh - 70px);overflow: auto;">
						<history :footers="footers" :shareId="taskid" :refresh="refresh" :title="'绘画'" :assembly="false"
							@resid="delex" @submit="getVuex">
						</history>
					</view>
				</view>
				<el-aside :width="historyW+'px'"></el-aside>
			</view>
			<view v-else class="p_content" :style="footers?'width: '+historyW+'px':'width:0px'">
				<view style="position: fixed;margin-left: 0px;margin-top: 45vh;z-index:1;">
					<view style="margin-left: -25px;background-color: #f2f2f2;padding: 8px;" @click="footers = !footers"
						:style="'width:200px;display: flex;justify-content: center;align-items: center;border-radius: 50%;width:15px ; height: 15px;'">
						<i v-if="footers" class="el-icon-arrow-right" style="font-size: 25px;"></i>
						<i v-else class="el-icon-arrow-left" style="font-size: 25px;"></i>
					</view>
				</view>
				<view
					style="height: calc(100vh - 122px);display: flex;justify-content: flex-start;align-items: center;overflow: auto;">
					<history :footers="false" :shareId="taskid" :refresh="refresh" :title="'绘画'" :assembly="false"
						@resid="delex" @submit="getVuex">
					</history>
				</view>
			</view>
		</el-container>
		<uv-toast ref="toast"></uv-toast>
		<uv-code unique-key="paintingCode" :seconds="5" @end="end" ref="code"></uv-code>
		<tabbars></tabbars>
	</view>
</template>

<script>
	// 引入
	import contents from '@/components/content/content';
	import history from '@/components/history/history';
	import tabbars from '@/components/tabbar/tabbar';
	import {
		index,
		task,
		api,
		apiId,
		getScroll,
		scroll,
		getName
	} from '@/common/api.js';
	import headers from '@/components/header/header.vue';
	import config from '@/common/config'
	import mjy from '@/pages/painting/aside/mjy.vue';
	import flux from '@/pages/painting/flux.vue';
	import kling from '@/pages/painting/kling.vue';
	import dalle from '@/pages/painting/dalle.vue';
	import gpt from '@/pages/painting/gpt.vue';
	import asided from '@/pages/aside/aside.vue';
	export default {
		components: {
			// 注册组件
			tabbars,
			contents,
			history,
			headers,
			asided,
			mjy,
			flux,
			kling,
			dalle,
			gpt,
		},
		data() {
			return {
				dialogueColor: '#F4F5F9',
				deepColor: '#4D4D4D',
				shallowColor: '#808080',
				lightColor: '#ccc',
				state: true,
				asideW: 70,
				x: 30, // 初始边框宽度
				activeIndex: 0,
				startX: 0, // 触摸开始的X坐标
				endX: 0, // 触摸结束的X坐标
				footers: false,
				tabbarsValue: '',
				content: '',
				tips: '',
				seconds: 10,
				aicurrent: 0,
				req: {},
				historyW: 130,

				lists: {},
				show: 0,
				list: null,
				isTask: false,
				taskid: '',
				refresh: '',
				strType: '',
				tooltip: '图片存在有效期限制，使用请自行转存图片',
				jobId: '',
				aiType: 'flux',
				loading: false,
				taskInfo: {},
			}
		},
		watch: {
			// aicurrent(newVal, oldVal) {
			// 	console.log(newVal);
			// },
			// aiType(newVal, oldVal) {
			// 	console.log(newVal);
			// },
			// strType(newVal, oldVal) {
			// 	console.log(newVal);
			// }
		},
		computed: {
			configType() {
				return this.aiType == 'mjy' ? this.strType : this.aiType;
			},
		},
		created() {
			this.tabbarsValue = this.pages();
		},
		onLoad(ee) {
			if (ee && ee.id) {
				this.ress(ee.id);
			}
		},
		mounted() {
			// console.log(this.$replacd([
			// 	"http://localhost:8080/dpc/@cdn_/attachments/1336246639006056461/1336549075432116304/aiden_nichols4897_A_cute_golden_python_smiling_meandering_throu_a59db22c-cecc-4b98-a90e-3443e64bbd30.png?ex=67a435d3&is=67a2e453&hm=d0e855ba983fae868d3ce49cd4664c351abf2ebbf86b581cf1d292ace88e6970&",
			// 	"http://localhost:8080/dpc/@mjcdn_/attachments/1336246639006056461/1336549075432116304/aiden_nichols4897_A_cute_golden_python_smiling_meandering_throu_a59db22c-cecc-4b98-a90e-3443e64bbd30.png?ex=67a435d3&is=67a2e453&hm=d0e855ba983fae868d3ce49cd4664c351abf2ebbf86b581cf1d292ace88e6970&",
			// 	"http://localhost:8080/dpc/@cdnc_/20250205/912d6432-2774-43eb-9f22-6a339290ac3btl.png",
			// 	"http://localhost:8080/dpc/@cdnc_/20250205/912d6432-2774-43eb-9f22-6a339290ac3btr.png",
			// 	"http://localhost:8080/dpc/@cdnc_/20250205/912d6432-2774-43eb-9f22-6a339290ac3bbl.png",
			// 	"http://localhost:8080/dpc/@cdnc_/20250205/912d6432-2774-43eb-9f22-6a339290ac3bbr.png"
			// ]));
		},
		methods: {
			customI(e) {
				this.aicurrent = e;
				this.empty();
			},
			empty() {
				this.taskid = '';
				this.list = [];
				this.taskInfo = {};
			},
			delex(i) {
				if (i.includes(this.taskid)) {
					this.list = [];
					this.taskInfo = {};
				}
			},
			async record() {
				if (this.list[0]) await scroll({
					content: this.list,
					id: this.taskid
				}, {
					custom: {
						auth: true,
						toast: false,
					},
				})
				this.refresh = uni.$uv.guid(20);
			},
			async prompt(prompt) {
				var that = this;
				return new Promise((resolve, reject) => {
					api(this.aiApi + '/midjourney/v1/promptCheck', {
						"prompt": prompt
					}, {
						custom: {
							auth: true,
							toast: true,
							catch: true,
						},
					}).then(e => {
						// console.log(e);
						if (e.status == 'SUCCESS') {
							resolve(true);
						} else {
							resolve(false);
							that.$refs.toast.show({
								type: 'error',
								message: e.message || "提示词审核未通过， 严禁使用敏感提示词， 多次违规操作将暂停账号使用。",
								duration: '3000'
							});
						}
					}).catch(e => {
						console.log(e);
						that.$refs.toast.show({
							type: 'error',
							message: e.msg || "发送失败！",
							duration: '3000'
						});
						resolve(false)
					})
				})
			},
			loaded() {
				if (this.loading) {
					this.$refs.toast.show({
						message: "生成中,请等待......",
						duration: '2500'
					});
					return true;
				}
				this.loading = true;
				return false;
			},
			sended() {
				this.$refs.toast.show({
					message: "发送中。。。",
					duration: '2000'
				});
			},
			async flux(con) {
				if (this.loaded()) return;
				var that = this;
				this.sended();
				var url = '';
				if (this.configType == 'flux') {
					url = '/flux/' + (con?.image[0] ? 'edits' : 'generate') + '?type=' + this.tabbarsValue;
				} else {
					url = '/midjourney/v1/imagine?type=' + this.tabbarsValue;
					if (!await this.prompt(con['prompt'])) {
						this.loading = false;
						return false;
					}
				}
				api(this.aiApi + url, con, {
					custom: {
						auth: true,
						toast: false,
						catch: true,
					},
				}).then(e => {
					if (e.status == 'SUCCESS') {
						if (e.data.jobId) {
							that.$refs.toast.show({
								message: "请求成功，生成中。。。"
							})
							this.jobId = e.data.jobId;
							this.aiId = e.aiId;
							this.taskid = e.taskid;
							setTimeout(function() {
								that.$refs.code.start();
							}, 5000)
							that.list = [{
								role: 'assistant',
								content: '',
								jobId: e.data.jobId,
								aiId: e.aiId,
								aiType: this.aiType,
								quota: 0
							}];
							this.record();
						}
					}
				}).catch(e => {
					console.error(e);
					this.loading = false;
					that.$refs.toast.show({
						type: 'error',
						message: e.msg || "发送失败！",
						duration: '3000'
					});
				})
			},
			async dalle(con) {
				if (this.loaded()) return;
				var that = this;
				this.sended();
				var url = '/openai/v1/images/generations?type=' + this.tabbarsValue;
				api(this.aiApi + url, con, {
					custom: {
						auth: true,
						toast: true,
						catch: true,
					},
				}).then(e => {
					if (e.status == 'SUCCESS') {
						that.$refs.toast.show({
							message: "生成图像成功！"
						})
						// console.log(e.data);
						this.taskid = e.taskid;
						this.list = [e.data];
						this.refresh = uni.$uv.guid(20);
						this.loading = false;
					}
				}).catch(e => {
					this.loading = false;
					this.list.splice(this.list.length - 1, 1);
					that.$refs.toast.show({
						type: 'error',
						message: e.msg || "发送失败！",
						duration: '3000'
					});
				})
			},
			async gpt(con) {
				if (this.loaded()) return;
				var that = this;
				this.sended();
				var url = '/openai/4o-image/generations?type=' + this.tabbarsValue;
				api(this.aiApi + url, con, {
					custom: {
						auth: true,
						toast: true,
						catch: true,
					},
				}).then(e => {
					if (e.status == 'SUCCESS') {
						if (e.data.jobId) {
							that.$refs.toast.show({
								message: "请求成功，生成中。。。"
							})
							this.jobId = e.data.jobId;
							this.aiId = e.aiId;
							this.taskid = e.taskid;
							setTimeout(function() {
								that.$refs.code.start();
							}, 5000)
							that.list = [{
								role: 'assistant',
								content: '',
								jobId: e.data.jobId,
								aiId: e.aiId,
								aiType: this.aiType,
								quota: 0
							}];
							this.record();
						}
					}
				}).catch(e => {
					this.loading = false;
					that.$refs.toast.show({
						type: 'error',
						message: e.msg || "发送失败！",
						duration: '3000'
					});
				})
			},
			end() {
				var that = this;
				var aiId = this.aiId ? this.aiId : this.list[this.list.length - 1].aiId;
				var jobId = this.jobId ? this.jobId : this.list[this.list.length - 1].jobId;
				var aiType = this.aiType ? this.aiType : this.list[this.list.length - 1].aiType;
				var url = '';
				if (aiType == 'flux') {
					url = '/flux/fetch?type=' + this.tabbarsValue + '&aiId=' + aiId
				} else if (aiType == 'mjy') {
					url = '/midjourney/v1/fetch?type=' + this.tabbarsValue + '&aiId=' + aiId
				} else if (aiType == 'gpt') {
					url = '/openai/4o-image/fetch?type=' + this.tabbarsValue + '&aiId=' + aiId
				} else {
					url = '/insightFace/v1/fetch?type=' + this.tabbarsValue + '&aiId=' + aiId
				}
				api(this.aiApi + url, {
					jobId: jobId,
					aiId: aiId
				}, {
					custom: {
						auth: true,
						// toast: false,
						catch: true,
					},
				}).then(e => {
					// console.log(e);
					if (e.status == 'SUCCESS') {
						var data = e.data;
						this.taskid = e.taskid;
						this.list.splice(this.list.length - 1, 1);
						data['createdAt'] = new Date;
						data['role'] = 'assistant';
						this.list = [data];
						this.record();
						this.loading = false;
					} else if (e.status == 'FAILED') {
						this.list.splice(this.list.length - 1, 1);
						this.loading = false;
						this.record();
						this.$refs.toast.show({
							type: 'error',
							message: e.message || '发送错误，请重新发送！',
							duration: '3000'
						})
					} else {
						setTimeout(function() {
							that.$refs.code.start();
						}, 1500)
					}
				}).catch(e => {
					this.loading = false;
					console.log(e);
				})
			},
			async getVuex(i = '') {
				var params = {
					type: this.tabbarsValue,
				};
				if (i) {
					params['id'] = i;
				}
				try {
					const e = await getScroll({
						custom: {
							auth: true,
							toast: false,
						},
						params: params
					});
					if (e.task && e.task.taskInfo) {
						this.taskInfo = e.task.taskInfo;
					}
					if (e[0] && e[0].task && e[0].task.taskInfo) {
						this.taskInfo = e[0].task.taskInfo;
					}
					this.aiType = 'flux';
					this.aicurrent = 0;
					var sapi = e?.task?.api;
					if (sapi == 'generate') {
						this.aiType = 'flux';
						this.aicurrent = 0;
					} else if (sapi == 'openai') {
						this.aiType = 'dalle'
						this.aicurrent = 1;
					} else if (sapi == "imagine") {
						this.aiType = 'mjy'
						this.aicurrent = 2;
					} else if (sapi == 'generations') {
						this.aiType = 'gpt'
						this.aicurrent = 3;
					}

					//  else if (sapi == 'generations'){
					// 	this.aiType = 'kling'
					// 	this.aicurrent = 4;
					// }
					if (e && e.content != []) {
						this.list = e.content;
						this.show = e.show;
						this.taskid = e._id;
					} else {
						this.taskid = '';
						this.list = [];
					}
					if (this.list && this.list.length && this.list[this.list.length - 1].aiId) {
						this.$refs.code.start();
					}
				} catch (error) {
					console.log(error);
				}
			},
			async ress(a) {
				try {
					const e = await getName('flow', {
						custom: {
							auth: true,
							toast: false,
						},
						params: {
							sid: a,
						}
					});
					if (e.data[0] && e.data[0].task) {
						this.taskInfo = e.data[0].task.taskInfo;
					}
					var sapi = e.data[0]?.task?.api;
					if (sapi == 'generate') {
						this.aiType = 'flux';
						this.aicurrent = 0;
					} else if (sapi == 'openai') {
						this.aiType = 'dalle'
						this.aicurrent = 1;
					} else if (sapi == "imagine") {
						this.aiType = 'mjy'
						this.aicurrent = 2;
					} else if (sapi == 'generations') {
						this.aiType = 'gpt'
						this.aicurrent = 3;
					}
					if (e.data[0] && e.data[0].content != []) {
						this.list = e.data[0].content;
						this.show = e.data[0].show;
						this.taskid = e.data[0].sid;
					} else {
						this.taskid = '';
						this.list = [];
					}
				} catch (error) {
					console.log(error);
				}
			},
			pages() {
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
				return currentPage.split('/')[2];
			},
			cTime(time1, e, index) {
				if (index == 0) {
					return true;
				}
				// console.log(" ” " + Number(e.length - 1));
				if (index == Number(e.length - 1)) {
					return false;
				}
				var time2 = e[index + 1] && e[index + 1].createdAt;
				if (!time1 || !time2) {
					return false;
				}
				// console.log(time1 + " 《=》 " + time2);
				// 将时间转换为Date对象
				var date1 = new Date(time1).getTime();
				var date2 = new Date(time2).getTime();
				// 计算时间差（毫秒）
				var difference = Math.abs(date2 - date1);
				// 将时间差转换为分钟
				var minutes = Math.ceil(difference / (1000 * 60)); // 向上取整
				if (minutes > 20) {
					return true;
				} else {
					return false;
				}
			},
			times(time) {
				return " -- " + uni.$uv.timeFrom(new Date(time).getTime()) + " -- ";
			},
			routes(url) {
				this.routed('/pages' + url);
			},
			routed(url) {
				console.log('routed', url)
				uni.$uv.route({
					url: url,
					intercept(params, next) {
						// console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.painting-index {
		-webkit-user-select: text;
		/* Safari */
		-moz-user-select: text;
		/* Firefox */
		-ms-user-select: text;
		/* IE 10+ */
		user-select: text;
		/* Standard syntax */

		height: 100vh;

		.p_content {
			box-shadow: 10px 10px 20px #ccc;
			padding: 10px 5px 0px;
			transition: width 1s;
			position: fixed;
			top: 50px;
			right: 0px;
			border: 1px solid #f2f2f2;
			border-top-left-radius: 10px;
			border-bottom-left-radius: 10px;
			background-color: #fff;
		}

		.middle_item {
			margin-bottom: 5px;
			display: flex;
			align-items: flex-start;
			width: 100%;
			flex-direction: row;
			flex-wrap: nowrap;
			align-content: stretch;
			justify-content: flex-start;

			.middle_pc {
				border-radius: 10px;
				padding: 10px;
				margin: 0px 5px;
			}

			.middle_os {
				border-radius: 10px;
				padding: 10px;
			}

			.selectable-text {
				-webkit-user-select: text;
				/* Safari */
				-moz-user-select: text;
				/* Firefox */
				-ms-user-select: text;
				/* IE 10+ */
				user-select: text;
				/* Standard syntax */
			}

			::v-deep .code-block {
				background-color: #f8f8f8;
				border: 1px solid #ddd;
				padding: 5px 10px;
				border-radius: 5px;
				white-space: pre-wrap;
				word-break: break-all;
				font-family: 'Courier New', Courier, monospace;
				font-size: 14px;
			}

			::v-deep .copy-text:hover {
				color: #409EFF;
			}

			.fill {
				width: 40px;
				height: 40px;
				border-radius: 20px;

				::v-deep .el-image__inner {
					width: 40px;
					height: 40px;
					border-radius: 20px;
				}
			}

		}

		.user {
			flex-direction: row-reverse;
		}

		.custom-footer {
			margin-right: 300px;
		}
	}
</style>